package com.euond.accv.gateway.filter;

import com.euond.accv.gateway.constant.FilterConstants;
import com.euond.accv.gateway.service.TokenService;
import com.euond.common.constant.TokenConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求头部增加SuperToken,绕过后端接口服务
 *
 * 对请求进行拦截与过滤
 * filterOrder:filter执行顺序，通过数字指定 
   shouldFilter:filter是否需要执行 true执行 false 不执行 
    run : filter具体逻辑 
	filterType :filter类型,分为以下几种
 */
public class SuperTokenFilter extends ZuulFilter {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 是否执行run方法
	 */
	@Override
	public boolean shouldFilter() {
		String retCode = (String)RequestContext.getCurrentContext().get("retCode");
		if(StringUtils.isNotBlank(retCode) && retCode.equals("0")) {
			return true;
		}
		return false;
	}

	@Override
	public Object run() {
		logger.info("run SuperToken Filter.....");

		RequestContext ctx = RequestContext.getCurrentContext();
        //HttpServletRequest request = ctx.getRequest();

		//设置头部为超级Token，访问是绕过拦截器
		ctx.addZuulRequestHeader(TokenConstants.HTTPHEAD_USER_TOKEN,TokenConstants.SUPER_TOKEN);
		ctx.set(FilterConstants.STATUS_CODE,"0");
        return null;
	}


	/**
	 * 	pre:请求执行之前filter 
		route: 处理请求，进行路由 
		post: 请求处理完成后执行的filter 
		error:出现错误时执行的filter
	 */
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 40;
	}

}
